<template>
  <d2-container>
    <template slot="header">
      <el-button size="small" type="primary" @click="showDialog(null)">新增模板</el-button>
    </template>
    <el-form :inline="true" :model="searchForm">
      <el-form-item label="模板名称">
        <el-input clearable size="small" v-model="searchForm.summary" placeholder="模板名称"></el-input>
      </el-form-item>
      <el-form-item label="标签" prop="tagId">
        <el-select clearable size="small" v-model="searchForm.tagId" placeholder="请选择标签">
          <el-option v-for="tag in tags" :key="tag.id" :label="tag.id + ':' + tag.name" :value="tag.id"></el-option>
        </el-select>
      </el-form-item>
        <el-form-item label="广告属性" :label-width="formLabelWidth" prop="adType">
          <el-select clearable v-model="searchForm.adType" placeholder="请选择广告属性">
            <el-option label="NONE:无广告" value="NONE"></el-option>
            <el-option label="SHOW:显示广告后使用" value="SHOW"></el-option>
          </el-select>
        </el-form-item>
      <el-form-item>
        <el-button size="small" type="plain" @click="templateList()">查询</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="tableLoading" :data="templates" style="width: 100%;" :stripe="true" :border="true">
      <el-table-column prop="id" label="模板ID" width="80"> </el-table-column>
      <el-table-column prop="summary" label="模板名称"> </el-table-column>
      <el-table-column prop="tagName" label="标签"> </el-table-column>
      <el-table-column prop="adTypeName" label="广告属性"> </el-table-column>
      <el-table-column prop="backgroundPic" label="背景图片">
        <template slot-scope="scope">
          <el-image :preview-src-list="[scope.row.backgroundPic]" style="width: 100px; height: 100px" :src="scope.row.backgroundPic" fit="fill"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="faceGif" label="动态GIF">
        <template slot-scope="scope">
          <el-image :preview-src-list="[scope.row.faceGif]" style="width: 100px; height: 100px" :src="scope.row.faceGif" fit="fill"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="coverPic" label="封面图">
        <template slot-scope="scope">
          <el-image :preview-src-list="[scope.row.coverPic]" style="width: 100px; height: 100px" :src="scope.row.coverPic" fit="fill"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="effectGif" label="效果图">
        <template slot-scope="scope">
          <el-image :preview-src-list="[scope.row.effectGif]" style="width: 100px; height: 100px" :src="scope.row.effectGif" fit="fill"></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="action" label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="showDialog(scope.row)">编辑</el-button>
          <el-button type="text" size="small" @click="deleteTemplate(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible">
      <el-form v-loading="editLoading" v-if="dialogVisible" :model="form" :rules="rules" ref="editForm">
        <el-row>
          <el-col :span="12">
            <el-form-item label="标签名称" :label-width="formLabelWidth" prop="summary">
              <el-input v-model="form.summary" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="标签" prop="tagId" :label-width="formLabelWidth">
              <el-select clearable v-model="form.tagId" placeholder="请选择标签">
                <el-option v-for="tag in tags" :key="tag.id" :label="tag.id + ':' + tag.name" :value="tag.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="背景图" :label-width="formLabelWidth" style="width:600px" prop="backgroundPic" required>
          <el-input v-show="false" v-model="form.backgroundPic"></el-input>
          <el-upload drag action="" :on-change="getFile" :limit="2" :file-list="fileList" list-type="picture" :auto-upload="false">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="动态GIF" :label-width="formLabelWidth" style="width:600px" prop="faceGif" required>
          <el-input v-show="false" v-model="form.faceGif"></el-input>
          <el-upload drag action="" :on-change="getFaceGifFile" :limit="2" :file-list="faceGifFileList" list-type="picture" :auto-upload="false">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
          </el-upload>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="祝福文字" :label-width="formLabelWidth" prop="textWord">
              <el-input v-model="form.textWord" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="文字位置" :label-width="formLabelWidth" style="width:600px" prop="wordPosition">
              <el-select clearable v-model="form.wordPosition" placeholder="请选择文字位置">
                <el-option label="left" value="LEFT"></el-option>
                <el-option label="right" value="RIGHT"></el-option>
                <el-option label="bottom" value="BOTTOM"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="广告属性" :label-width="formLabelWidth" prop="adType">
          <el-select clearable v-model="form.adType" placeholder="请选择广告属性">
            <el-option label="NONE:无广告" value="NONE"></el-option>
            <el-option label="SHOW:显示广告后使用" value="SHOW"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit()">确 定</el-button>
      </span>
    </el-dialog>
    <template slot="footer">
      <p align="right">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPageInfo.current" :page-sizes="pageSizeOptions" :page-size="currentPageInfo.size" layout="total, sizes, prev, pager, next, jumper" :total="currentPageInfo.total">
        </el-pagination>
      </p>
    </template>
  </d2-container>
</template>

<script>
import api from "@/api";
export default {
  data () {
    return {
      fileList: [],
      faceGifFileList: [],
      searchForm: {},
      tableLoading: false,
      tags: [],
      currentPageInfo: {
        current: 1,
        size: 10,
        total: 0
      },
      pageSizeOptions: [5, 10, 20, 40],
      editLoading: false,
      formLabelWidth: "120px",
      form: {
        backgroundPic: "",
        faceGif: "",
        summary: "",
        tagId: "",
        adType: "NONE"
      },
      templates: [],
      currentTemplate: null,
      dialogVisible: false,
      rules: {
        summary: [
          { required: true, message: "请输入模板名称", trigger: "blur" },
          {
            min: 0,
            max: 32,
            message: "长度在 0 到 255 个字符",
            trigger: "blur"
          }
        ],
        tagId: [{ required: true, message: "请选择模板标签", trigger: "blur" }],
        faceGif: [
          { required: true, message: "请上传动态GIF", trigger: "blur" }
        ],
        backgroundPic: [
          { required: true, message: "请上传背景图片", trigger: "blur" }
        ]
      }
    };
  },
  computed: {
    dialogTitle () {
      return this.currentTemplate == null
        ? "新增模板"
        : "编辑模板 - " + this.currentTemplate.summary;
    },
    isNew () {
      return this.currentTemplate == null;
    }
  },
  methods: {
    updateView () {
      this.$forceUpdate()
    },
    getFile (file, fileList) {
      if (file.raw.type != "image/jpeg" && file.raw.type != "image/png") {
        this.$message({
          message: "仅允许上传jpg、png格式的图片！",
          type: "error"
        });
        this.form.backgroundPic = "";
        this.$nextTick(() => {
          this.fileList = [];
        });
        return;
      }
      this.getBase64(file.raw).then(res => {
        this.$nextTick(() => {
          this.fileList = [{ name: "", url: res }];
          this.form.backgroundPic = res;
        });
      });
    },
    getFaceGifFile (file, fileList) {
      if (file.raw.type != "image/gif") {
        this.$message({
          message: "仅允许上传gif格式的图片！",
          type: "error"
        });
        this.$nextTick(() => {
          this.faceGifFileList = [];
          this.form.faceGif = "";
        });
        return;
      }
      this.getBase64(file.raw).then(res => {
        this.faceGifFileList = [{ name: "", url: res }];
        this.form.faceGif = res;
      });
    },
    getBase64 (file) {
      return new Promise(function(resolve, reject) {
        let reader = new FileReader();
        let imgResult = "";
        reader.readAsDataURL(file);
        reader.onload = function() {
          imgResult = reader.result;
        };
        reader.onerror = function(error) {
          reject(error);
        };
        reader.onloadend = function() {
          resolve(imgResult);
        };
      });
    },
    handleSizeChange (val) {
      this.currentPageInfo.size = val;
      this.currentPageInfo.current = 1;
      this.templateList();
    },
    handleCurrentChange (val) {
      this.currentPageInfo.current = val;
      this.templateList();
    },
    showDialog (currentTemplate) {
      this.fileList = [];
      this.faceGifFileList = [];
      this.currentTemplate = currentTemplate;
      this.form = currentTemplate
        ? JSON.parse(JSON.stringify(currentTemplate))
        : {
          backgroundPic: "",
          faceGif: "",
          summary: "",
          tagId: "",
          adType: "NONE"
        };
      if (currentTemplate) {
        this.fileList = [{ name: "", url: currentTemplate.backgroundPic }];
        this.faceGifFileList = [{ name: "", url: currentTemplate.faceGif }];
      }
      this.dialogVisible = true;
    },
    deleteTemplate (template) {
      this.$confirm("确定要删除吗？", "删除模板", {
        type: "warning"
      }).then(async _ => {
        var res = await api.service.delete("/backManage/templates", {
          params: {
            ids: template.id
          }
        }).catch(function(error) { });
        if (res) {
          this.$message({
            message: "删除成功！",
            type: "success"
          });
          this.templateList();
        }
      });
    },
    submit () {
      this.$refs.editForm.validate(async valid => {
        if (valid) {
          this.editLoading = true;
          var res = await api.service
            .post("/backManage/template", this.form)
            .catch(function(error) { });
          if (res) {
            this.$message({
              message: this.isNew ? "新增成功！" : "修改成功！",
              type: "success"
            });
            this.dialogVisible = false;
            this.templateList();
          }
          this.editLoading = false;
        }
      });
    },
    async templateList () {
      this.tableLoading = true;
      var data = await api.service.get("/backManage/templates", {
        params: {
          summary: this.searchForm.summary,
          tagId: this.searchForm.tagId,
          adType: this.searchForm.adType,
          currentPage: this.currentPageInfo.current,
          pageSize: this.currentPageInfo.size
        }
      }).catch(function(error) { });
      this.currentPageInfo = data;
      if (this.tags.length < 1) {
        await this.tagList();
      }
      this.templates = data.records.map(template => {
        for (var i = 0; i < this.tags.length; i++) {
          if (template.tagId == this.tags[i].id) {
            template.tagName = this.tags[i].id + ":" + this.tags[i].name;
          }
        }
        if (template.adType == 'NONE') {
          template.adTypeName = 'NONE:无广告'
        }
        if (template.adType == 'SHOW') {
          template.adTypeName = 'SHOW:显示广告后使用'
        }
        return template;
      });
      this.tableLoading = false;
    },
    async tagList () {
      this.tableLoading = true;
      var data = await api.service.get("/backManage/tags");
      this.tags = data.records;
    }
  },
  async created () {
    this.tagList();
    this.templateList();
  }
};
</script>
